package com.ideaction.service;

import com.ideaction.consts.ReturnKeyConst;
import com.ideaction.entity.player.Player;
import com.ideaction.game.utils.JsonUtils;
import com.ideaction.game.utils.SimpleDBUtil;
import com.ideaction.globalconst.NoticeKeyConst;
import com.ideaction.globalconst.Result;
import com.ideaction.log.dblog.RegistLog;
import com.ideaction.req.PlayerCommonReqBody;
import com.log.service.GameLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class LoginServiceImp {
    
    @Autowired
    private MongoTemplate playerMongoTemplate;
    
    @Autowired
    private GameLogService gameLogService;
    
    /**
     * 玩家登陆
     *
     * @param playerLoginReqBody
     * @param ip
     * @return
     */
    public String login(PlayerCommonReqBody playerLoginReqBody, String ip) {
        Result r = Result.build();
        String userId = playerLoginReqBody.getUserId();
        Player player;
        if (!SimpleDBUtil.existsPlayer(playerMongoTemplate, userId)) {
            player = new Player(userId, ip, playerLoginReqBody);
            playerMongoTemplate.save(player);
            log.info("自动注册玩家,userId: " + userId + " ip: " + ip);
            // 数据库日志,自动记录本地日志 demo
            RegistLog dblog = new RegistLog(playerLoginReqBody.getUserId(), ip);
            gameLogService.dbExcute(dblog);
        } else {
            player = SimpleDBUtil.findDataByUserId(playerMongoTemplate, userId, Player.class);
            if (player.getPlayerClientData() != null) {
                r.put("PlayerClientData", JsonUtils.toJson(player.getPlayerClientData()));
            }
        }
        log.info("玩家登陆成功,userId: " + userId + " ip: " + ip);
        r.put(ReturnKeyConst.TIME_STAMP, System.currentTimeMillis() / 1000);
        return r.response();
    }
    
    public String loginHttpMessageProcessor(PlayerCommonReqBody playerLoginReqBody) {
        String userID = playerLoginReqBody.getUserId();
        String language = playerLoginReqBody.getParam("Language");
        Result r = Result.build();
        
        if (!SimpleDBUtil.existsPlayer(playerMongoTemplate, userID)) {
            return r.error(NoticeKeyConst.USER_NOT_EXIST, language);
        }
        
        Player player = SimpleDBUtil.findDataByUserId(playerMongoTemplate, userID, Player.class);
        r.put("Player", player.getPlayerClientData());
        return r.response();
    }
}
